#include <memory>
#include "EpollServer.hpp"
#include "circularQueue.hpp"

Response Calculator(Request req)
{
    Response resp;
    switch (req._op)
    {
    case '+':
        resp._result = req._x + req._y;
        break;
    case '-':
        resp._result = req._x - req._y;

        break;
    case '*':
        resp._result = req._x * req._y;

        break;
    case '/':
        if(req._y == 0)
            resp._code = 1;
        else
            resp._result = req._x / req._y;
        break;
    case '%':
        if(req._y == 0)
            resp._code = 0;
        else
            resp._result = req._x % req._y;
        break;
    default:
        resp._code = 2;
    }
    return resp;
}


// 生产者： reactor + listensock
// InitServer + Dispatcher
// 消费者： reactor + sock
// Exchter：从任务队列中捞取 sock
void *consumer(void *args)
{
    pthread_detach(pthread_self());
    cout << "consumer..." << endl;
    circularQueue<Connection*> *cq = static_cast<circularQueue<Connection*> *>(args);
    std::unique_ptr<EpollServer> svr(new EpollServer(Calculator,cq));   
    svr->Executer();
    return nullptr;
}

void *producer(void *args)
{
    // 先让消费者把epoll模型创建好
    sleep(1);
    cout << "producer..." << endl;
    circularQueue<Connection*> *cq = static_cast<circularQueue<Connection*> *>(args);
    std::unique_ptr<EpollServer> svr(new EpollServer(Calculator,cq));   
    svr->InitServer();
    svr->Dispatcher();
    return nullptr;
}

int main()
{
    // 让生产者消费者看到同一个资源
    circularQueue<Connection*> *cq = new circularQueue<Connection*>();
    pthread_t c[3], p;
    for(int i = 0; i < 3; i++)
        pthread_create(c+i, nullptr, consumer, cq);
    pthread_create(&p, nullptr, producer, cq);
    pthread_join(p, nullptr);
    
    return 0;
}